package org.grayrabbit.cloud.core.module;

import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

import org.grayrabbit.cloud.core.Context;
import org.grayrabbit.cloud.core.biz.BizArgument;
import org.grayrabbit.cloud.core.biz.BizResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ProxyModuleContext implements
		Context<String, Proxy<BizResult, BizArgument>> {
	private static final Logger logger = LoggerFactory.getLogger(ProxyModuleContext.class);
	private final static ProxyModuleContext context = new ProxyModuleContext();
	public static ProxyModuleContext getInstance(){
		return context;
	}
	private static Map<String, Queue<Proxy<BizResult, BizArgument>>> proxyModules = new ConcurrentHashMap<String, Queue<Proxy<BizResult, BizArgument>>>();

	@Override
	public Set<String> getKeys() {
		return proxyModules.keySet();
	}

	@Override
	public Proxy<BizResult, BizArgument> getValue(String k) {
		if(k==null)
			return null;
		Queue<Proxy<BizResult, BizArgument>> proxies = proxyModules.get(k);
		if(proxies.size()<=0)
			return null;
		//TODO 算法取哪个远程模块服务；
		return calcProxy(proxies);
	}

	@Override
	public void setValue(String key, Proxy<BizResult, BizArgument> v) {
		logger.debug("设置:{}",key);
		Queue<Proxy<BizResult, BizArgument>> proxies = proxyModules.get(key);
		if(proxies==null){
			proxies = new LinkedBlockingQueue<Proxy<BizResult,BizArgument>>();
			proxies.offer(v);
		}else{
			if(!proxies.contains(v)){
				proxies.offer(v);
			}
		}
		
		proxyModules.put(key, proxies);
	}

	//使用队列的方式进行轮询,存在为null的情况
	private Proxy<BizResult, BizArgument> calcProxy(Queue<Proxy<BizResult, BizArgument>> proxies){
		Proxy<BizResult, BizArgument> proxy = proxies.poll();
		proxies.offer(proxy);
		return proxy;
	}
}
